"""
变量管理API
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.extensions import db
from app.models import Variable
from datetime import datetime

variables_bp = Blueprint('variables', __name__, url_prefix='/api/variables')

# 变量分类常量
VARIABLE_CATEGORIES = {
    'product': '产品相关',
    'system': '系统相关', 
    'workshop': '车间相关',
    'url': 'URL',
    'sql': 'SQL'
}


@variables_bp.route('/categories', methods=['GET'])
@jwt_required()
def get_variable_categories():
    """获取变量分类列表"""
    try:
        return jsonify({
            'categories': [
                {'key': key, 'name': name} 
                for key, name in VARIABLE_CATEGORIES.items()
            ]
        }), 200
    except Exception as e:
        return jsonify({'message': f'获取变量分类失败: {str(e)}'}), 500


@variables_bp.route('', methods=['GET'])
@jwt_required()
def get_variables():
    """获取变量列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '')
        category = request.args.get('category', '')
        
        query = Variable.query
        
        if search:
            query = query.filter(
                (Variable.name.contains(search)) | 
                (Variable.key.contains(search)) |
                (Variable.description.contains(search))
            )
        
        if category:
            query = query.filter(Variable.category == category)
        
        pagination = query.order_by(Variable.created_at.desc()).paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        variables = [var.to_dict() for var in pagination.items]
        
        return jsonify({
            'variables': variables,
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page,
            'per_page': per_page
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'获取变量列表失败: {str(e)}'}), 500


@variables_bp.route('', methods=['POST'])
@jwt_required()
def create_variable():
    """创建变量"""
    try:
        data = request.get_json()
        name = data.get('name', '').strip()
        key = data.get('key', '').strip()
        value = data.get('value', '').strip()
        category = data.get('category', '').strip()
        description = data.get('description', '').strip()
        is_active = data.get('is_active', True)
        
        # 验证必填字段
        if not name:
            return jsonify({'message': '变量名称不能为空'}), 400
        if not key:
            return jsonify({'message': '变量键名不能为空'}), 400
        if not value:
            return jsonify({'message': '变量值不能为空'}), 400
        if not category:
            return jsonify({'message': '变量分类不能为空'}), 400
        
        # 验证分类是否有效
        if category not in VARIABLE_CATEGORIES:
            return jsonify({'message': '无效的变量分类'}), 400
        
        # 检查键名是否已存在
        if Variable.query.filter_by(key=key).first():
            return jsonify({'message': '变量键名已存在'}), 400
        
        # 创建变量
        variable = Variable(
            name=name,
            key=key,
            value=value,
            category=category,
            description=description,
            is_active=is_active
        )
        
        db.session.add(variable)
        db.session.commit()
        
        return jsonify({
            'message': '变量创建成功',
            'variable': variable.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建变量失败: {str(e)}'}), 500


@variables_bp.route('/<int:variable_id>', methods=['PUT'])
@jwt_required()
def update_variable(variable_id):
    """更新变量"""
    try:
        variable = Variable.query.get(variable_id)
        if not variable:
            return jsonify({'message': '变量不存在'}), 404
        
        data = request.get_json()
        
        # 更新字段
        if 'name' in data:
            name = data['name'].strip()
            if not name:
                return jsonify({'message': '变量名称不能为空'}), 400
            variable.name = name
        
        if 'key' in data:
            key = data['key'].strip()
            if not key:
                return jsonify({'message': '变量键名不能为空'}), 400
            if key != variable.key:
                if Variable.query.filter_by(key=key).first():
                    return jsonify({'message': '变量键名已存在'}), 400
                variable.key = key
        
        if 'value' in data:
            value = data['value'].strip()
            if not value:
                return jsonify({'message': '变量值不能为空'}), 400
            variable.value = value
        
        if 'category' in data:
            category = data['category'].strip()
            if not category:
                return jsonify({'message': '变量分类不能为空'}), 400
            if category not in VARIABLE_CATEGORIES:
                return jsonify({'message': '无效的变量分类'}), 400
            variable.category = category
        
        if 'description' in data:
            variable.description = data['description'].strip()
        
        if 'is_active' in data:
            variable.is_active = data['is_active']
        
        # 更新时间
        variable.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return jsonify({
            'message': '变量更新成功',
            'variable': variable.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新变量失败: {str(e)}'}), 500


@variables_bp.route('/<int:variable_id>', methods=['DELETE'])
@jwt_required()
def delete_variable(variable_id):
    """删除变量"""
    try:
        variable = Variable.query.get(variable_id)
        if not variable:
            return jsonify({'message': '变量不存在'}), 404
        
        db.session.delete(variable)
        db.session.commit()
        
        return jsonify({'message': '变量删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'删除变量失败: {str(e)}'}), 500


@variables_bp.route('/batch', methods=['DELETE'])
@jwt_required()
def batch_delete_variables():
    """批量删除变量"""
    try:
        data = request.get_json()
        variable_ids = data.get('ids', [])
        
        if not variable_ids:
            return jsonify({'message': '请选择要删除的变量'}), 400
        
        variables = Variable.query.filter(Variable.id.in_(variable_ids)).all()
        
        if not variables:
            return jsonify({'message': '未找到要删除的变量'}), 404
        
        for variable in variables:
            db.session.delete(variable)
        
        db.session.commit()
        
        return jsonify({
            'message': f'成功删除 {len(variables)} 个变量'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'批量删除变量失败: {str(e)}'}), 500


@variables_bp.route('/<int:variable_id>', methods=['GET'])
@jwt_required()
def get_variable(variable_id):
    """获取单个变量详情"""
    try:
        variable = Variable.query.get(variable_id)
        if not variable:
            return jsonify({'message': '变量不存在'}), 404
        
        return jsonify({
            'variable': variable.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'获取变量详情失败: {str(e)}'}), 500